
package com.feib.soeasy.dao.hibernate;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;

import com.feib.soeasy.dao.RoleDao;
import com.feib.soeasy.model.Group;
import com.feib.soeasy.model.Role;

/**
 * @title (#)RoleHibernateDao.java<br>
 * @description <br>
 * @author Anson Tsai<br>
 * @version 1.0.0 2010/11/25
 * @copyright Far Eastern International Bank Copyright (c) 2010<br>
 * @2010/11/14 create by Anson Tsai<br>
 */
@Repository("roleDao")
public class RoleHibernateDao extends BaseHibernateDao<Role, Long> implements RoleDao
{

    @Override
    public List<Role> findByGroupNo(String groupNo) {
        DetachedCriteria criteria = DetachedCriteria.forClass(this.getPersistentClass());
        criteria.setResultTransformer(DetachedCriteria.DISTINCT_ROOT_ENTITY);

        DetachedCriteria detachedCriteria = criteria.createCriteria("group");
        detachedCriteria.add(Restrictions.eq("groupNo", groupNo));

        @SuppressWarnings("unchecked")
        List<Role> roles = this.getHibernateTemplate().findByCriteria(criteria);

        return roles;
    }

    /* (non-Javadoc)
     * @see com.feib.soeasy.dao.RoleDao#countRoleByGroupExcludeAdmin(com.feib.soeasy.model.Group)
     */
    @Override
    public int countRoleByGroupExcludeAdmin(Group group) {

        DetachedCriteria criteria = DetachedCriteria.forClass(this.getPersistentClass());
        criteria.setResultTransformer(DetachedCriteria.DISTINCT_ROOT_ENTITY);       

        
        // 限定不是 ADMINISTRATOR
        criteria.add(Restrictions.not(Restrictions.eq("roleNo", "ADMINISTRATOR")));

        DetachedCriteria detachedCriteria = criteria.createCriteria("group");
        detachedCriteria.add(Restrictions.idEq(group.getGroupPk()));

        return countByDetachedCriteria(criteria);
    }

    /* (non-Javadoc)
     * @see com.feib.soeasy.dao.RoleDao#deleteByGroup(com.feib.soeasy.model.Group)
     */
    @SuppressWarnings("unchecked")
    @Override
    public void deleteByGroup(Group group) {
        StringBuffer hql = new StringBuffer();
        hql.append("from Role ");
        hql.append("where group = :group ");
        Query query = getSession().createQuery(hql.toString());
        query.setParameter("group", group);
        List<Role> roles = query.list();
        
        for(Role entity: roles)
            this.delete(entity);
        
    }

}
